package cn.itcast.bos.web.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.WayBillService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {

	Logger logger = Logger.getLogger(WayBillAction.class);
	@Autowired
	private WayBillService wayBillService;
	
	@Action(value="wayBill_save",results={@Result(name="success",type="json")})
	public String save() {
		if(model.getOrder() !=null && (model.getOrder().getId() ==null || model.getOrder().getId() ==0)) {
			model.setOrder(null);
		}
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			wayBillService.save(model);
			//保存成功
			map.put("success", true);
			map.put("msg", "运单保存成功！");
			logger.info("保存运单成功,运单号为："+model.getWayBillNum());
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("msg", "运单保存失败！");
			logger.error("保存运单成功,运单号为："+model.getWayBillNum(),e);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	@Action(value="wayBill_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery() {
		Pageable pageable = new PageRequest(page-1, rows,new Sort(new Sort.Order(Sort.Direction.ASC, "id")));
		Page<WayBill> pageData = wayBillService.findPageDate(model,pageable);
		pushPageDataToValueStack(pageData);
		return SUCCESS;
	}
	
	@Action(value="wayBill_findByWayBillNum",results={@Result(name="success",type="json")})
	public String findByWayBillNum() {
		Map<String,Object> map = new HashMap<String,Object>();
		WayBill wayBill = wayBillService.findByWayBillNum(model.getWayBillNum());
		if(wayBill == null) {
			map.put("success", false);
		}else {
			map.put("success", true);
			map.put("wayBillData", wayBill);
		}
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
}
